package ru.alt22.visor.php.core.codegen;

import java.util.ArrayList;

import org.eclipse.php.internal.core.phpModel.phpElementData.PHPFunctionData;

public class PHPInterface extends PHPIndentable {

	private ArrayList<String> superclasses;
	private ArrayList<PHPMethod> methods;

	public PHPInterface(String name) {
		this(name, new String[0]);
	}
	
	public PHPInterface(String name, String[] superclasses) {
		this(name, superclasses, new PHPMethod[0]);
	}

	public PHPInterface(String name, String[] superclasses, PHPMethod[] methods) {
		super(name);
		this.superclasses = new ArrayList<String>();
		this.methods = new ArrayList<PHPMethod>();
		for (int i = 0; i < superclasses.length; i++) {
			addSuperclass(superclasses[i]);
		}
		for (int i = 0; i < methods.length; i++) {
			addMethod(methods[i].getModifiers(), methods[i].getName());
		}
	}

	public void addSuperclass(String newInterface) {
		if (superclasses.contains(newInterface)) {
			return;
		}
		superclasses.add(newInterface);
	}

	public ArrayList<String> getSuperclasses() {
		return superclasses;
	}

	public void addMethod(PHPFunctionData method) {
		addMethod(method.getModifiers(), method.getName());
	}

	public void addMethod(int modifiers, String name) {
		PHPMethod newMethod = new PHPMethod(modifiers, name);
		if (methods.contains(newMethod)) {
			return;
		}
		methods.add(newMethod);
	}

	public void addMethodParameter(String methodName, String parameterName, String type, String defaultValue) {
		for (int i = 0; i < methods.size(); i++) {
			PHPMethod method = (PHPMethod) methods.get(i);
			if (!method.getName().equalsIgnoreCase(methodName)) {
				continue;
			}
			method.addParameter(parameterName, type, defaultValue);
		}
	}

	public ArrayList<PHPMethod> getMethods() {
		return methods;
	}

	public String toString(int indent) {
		StringBuffer result = new StringBuffer();

		result.append(indent(indent) + getSignature() + " {\n");
		result.append("\n");
		for (int i = 0; i < getMethods().size(); i++) {
			PHPMethod method = (PHPMethod) getMethods().get(i);
			result.append(method.toString(indent + 1, false));
			result.append("\n");
		}
		if (result.charAt(result.length() - 1) != '\n') {
			result.append("\n");
		}
		result.append(indent(indent) + "}\n");

		return result.toString();
	}

	private String getSignature() {
		StringBuffer result = new StringBuffer();

		result.append("interface ");
		result.append(getName());
		
		if (getSuperclasses().size() > 0) {
			result.append(" extends ");
			for (int i = 0; i < getSuperclasses().size(); i++) {
				result.append(getSuperclasses().get(i));
				if (i != getSuperclasses().size() -  1) {
					result.append(", ");
				}
			}
		}

		return result.toString();
	}

}